package com.zy.is.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.zy.is.common.config.AppConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: CaptchaController
 * @Description: 验证码控制器
 * @Author: Yanzy
 * @Data: 2021/4/6 16:45
 * @Source: 1.0
 */
@Slf4j
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    @GetMapping(value = "/captchaImg")
    public ModelAndView getCaptchaImg(HttpServletRequest request, HttpServletResponse response) {

        ServletOutputStream out = null;
        ICaptcha captcha = null;
        try {
            HttpSession session = request.getSession();
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");

            // 使用hutool工具, 生成验证码
            captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
            // 存入缓存
            session.setAttribute(AppConstants.CAPTCHA_KEY, captcha.getCode());
            out = response.getOutputStream();
            captcha.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
